from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QTextEdit, QLineEdit, QLabel, QFileDialog, QMessageBox
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont
from datetime import datetime
import pandas as pd
import os
from main_controller import MainController
from ui_state_manager import UIStateManager


class CentralWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.controller = MainController(self)
        self.ui_manager = UIStateManager(self)
        self.recognized_name = None  # 存储识别到的姓名
        self.init_ui()

    def init_ui(self):
        """初始化用户界面"""
        # 主布局
        main_layout = QVBoxLayout()

        # 姓名输入区域
        name_layout = QHBoxLayout()
        self.name_label = QLabel("姓名:")
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入姓名，用于绑定人脸数据")
        name_layout.addWidget(self.name_label)
        name_layout.addWidget(self.name_input)

        # 创建按钮区域
        button_layout = QHBoxLayout()

        # 创建按钮
        self.btn_input = QPushButton("录入信息")
        self.btn_view = QPushButton("查看信息")
        self.btn_face = QPushButton("人脸识别")
        self.btn_attendance = QPushButton("查看考勤")
        self.btn_export = QPushButton("导出考勤")
        self.btn_save = QPushButton("保存人脸")
        self.btn_stop = QPushButton("停止摄像")
        self.btn_clock_in = QPushButton("上班")
        self.btn_clock_out = QPushButton("下班")
        self.btn_clear = QPushButton("清空信息")

        # 将按钮添加到布局
        button_layout.addWidget(self.btn_input)
        button_layout.addWidget(self.btn_view)
        button_layout.addWidget(self.btn_face)
        button_layout.addWidget(self.btn_attendance)
        button_layout.addWidget(self.btn_export)
        button_layout.addWidget(self.btn_save)
        button_layout.addWidget(self.btn_stop)
        button_layout.addWidget(self.btn_clock_in)
        button_layout.addWidget(self.btn_clock_out)
        button_layout.addWidget(self.btn_clear)

        # 创建信息展示区域
        self.info_display = QTextEdit()
        self.info_display.setPlaceholderText("📋 信息显示区域\n💡 点击相应按钮查看详细信息\n🔍 支持的功能：\n  • 查看信息 - 显示已录入人员统计\n  • 查看考勤 - 显示详细考勤报告\n  • 人脸识别 - 实时识别并显示结果")
        
        # 设置信息显示区域的样式
        self.info_display.setFont(QFont("Consolas", 9))
        self.info_display.setStyleSheet("""
            QTextEdit {
                background-color: #f8f9fa;
                border: 2px solid #e9ecef;
                border-radius: 8px;
                padding: 10px;
                line-height: 1.4;
            }
            QTextEdit:focus {
                border-color: #007bff;
            }
        """)
        
        # 设置为只读
        self.info_display.setReadOnly(True)

        # 摄像头预览
        self.video_label = QLabel("摄像头预览将在这里显示")
        self.video_label.setMinimumHeight(240)

        # 将组件添加到主布局
        main_layout.addLayout(name_layout)
        main_layout.addLayout(button_layout)
        main_layout.addWidget(self.video_label)
        main_layout.addWidget(self.info_display)

        # 设置布局
        self.setLayout(main_layout)

        # 初始隐藏部分控件
        self.name_label.setVisible(False)
        self.name_input.setVisible(False)
        self.btn_save.setVisible(False)
        self.btn_stop.setVisible(False)
        self.btn_clock_in.setVisible(False)
        self.btn_clock_out.setVisible(False)

        # 连接信号和槽
        self.connect_signals()

    def connect_signals(self):
        """连接按钮信号到控制器方法"""
        self.btn_input.clicked.connect(self.controller.input.on_input_clicked)
        self.btn_view.clicked.connect(self.controller.view_controller.on_view_clicked)
        self.btn_face.clicked.connect(self.controller.face.on_face_clicked)
        self.btn_attendance.clicked.connect(self.controller.attendance.on_attendance_clicked)
        self.btn_export.clicked.connect(self.export_today_attendance)
        self.btn_save.clicked.connect(self.controller.input.on_save_clicked)
        self.btn_stop.clicked.connect(self.controller.input.on_stop_clicked)
        self.btn_clock_in.clicked.connect(self.controller.attendance.on_clock_in_clicked)
        self.btn_clock_out.clicked.connect(self.controller.attendance.on_clock_out_clicked)
        self.btn_clear.clicked.connect(self.clear_display)

    def update_display(self, message):
        """更新信息显示区域"""
        # 添加时间戳（除非消息已经包含时间戳或是分隔符）
        if not any(char in message for char in ['=', '-', '📊', '📋', '👥', '📅', '🕒']) and len(message.strip()) > 0:
            timestamp = datetime.now().strftime("%H:%M:%S")
            formatted_message = f"[{timestamp}] {message}"
        else:
            formatted_message = message
        
        self.info_display.append(formatted_message)
        
        # 自动滚动到底部
        scrollbar = self.info_display.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())

    def clear_display(self):
        """清空信息显示区域"""
        from display_formatter import DisplayFormatter
        
        self.info_display.clear()
        # 使用格式化工具显示清空提示
        cleared_messages = DisplayFormatter.create_empty_state_message('cleared')
        for msg in cleared_messages:
            self.info_display.append(msg)

    def export_today_attendance(self):
        """导出今日考勤表"""
        try:
            # 获取今日日期
            today = datetime.now().strftime("%Y-%m-%d")
            
            # 从数据库获取今日考勤数据
            attendance_data = self.controller.attendance.get_today_attendance_data()
            
            if not attendance_data:
                QMessageBox.information(self, "提示", "今日暂无考勤数据可导出")
                return
            
            # 选择保存路径
            default_filename = f"考勤表_{today}.xlsx"
            file_path, _ = QFileDialog.getSaveFileName(
                self,
                "保存考勤表",
                default_filename,
                "Excel文件 (*.xlsx);;CSV文件 (*.csv)"
            )
            
            if not file_path:
                return
            
            # 准备导出数据
            export_data = []
            for record in attendance_data:
                export_data.append({
                    '姓名': record.get('name', ''),
                    '日期': record.get('date', ''),
                    '上班时间': record.get('clock_in_time', ''),
                    '下班时间': record.get('clock_out_time', ''),
                    '工作时长': record.get('work_duration', ''),
                    '状态': record.get('status', '')
                })
            
            # 创建DataFrame
            df = pd.DataFrame(export_data)
            
            # 根据文件扩展名选择导出格式
            if file_path.endswith('.xlsx'):
                # 导出为Excel
                with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
                    df.to_excel(writer, sheet_name=f'考勤表_{today}', index=False)
                    
                    # 获取工作表并设置列宽
                    worksheet = writer.sheets[f'考勤表_{today}']
                    for column in worksheet.columns:
                        max_length = 0
                        column_letter = column[0].column_letter
                        for cell in column:
                            try:
                                if len(str(cell.value)) > max_length:
                                    max_length = len(str(cell.value))
                            except:
                                pass
                        adjusted_width = min(max_length + 2, 50)
                        worksheet.column_dimensions[column_letter].width = adjusted_width
                        
            elif file_path.endswith('.csv'):
                # 导出为CSV
                df.to_csv(file_path, index=False, encoding='utf-8-sig')
            
            # 显示成功消息
            QMessageBox.information(
                self, 
                "导出成功", 
                f"今日考勤表已成功导出到：\n{file_path}\n\n共导出 {len(export_data)} 条记录"
            )
            
            # 在信息显示区域显示导出信息
            self.update_display(f"📊 考勤表导出成功")
            self.update_display(f"📁 文件路径: {file_path}")
            self.update_display(f"📋 导出记录数: {len(export_data)} 条")
            
        except Exception as e:
            error_msg = f"导出失败: {str(e)}"
            QMessageBox.critical(self, "导出错误", error_msg)
            self.update_display(f"❌ {error_msg}")

    def reset_camera_and_controls(self):
        """统一重置：关闭摄像头并隐藏相关控件"""
        self.ui_manager.reset_all_controls()